#!/bin/env python
# coding:utf-8

import redis
from generate_rediskey import login_key, pay_key


class RedisHelper(object):
    _pool = None
    _conn = None
    _pipeline = None


    def __init__(self, redis_confg):
        self._pool = redis.ConnectionPool(
            host=redis_confg['host'],
            port=redis_confg['port'])

        self._conn = redis.Redis(connection_pool=self._pool)
        self._pipeline = self._conn.pipeline()


    # 计算出新增用户和活跃用户
    def user_login(self, login_time, create_time, main_channel, sub_channel, game_id, user_id):




        # 获得所需的key
        new_user_key_result = login_key(create_time, main_channel, sub_channel, game_id)
        login_user_key_result = login_key(login_time, main_channel, sub_channel, game_id)


        new_user_key = new_user_key_result['new_user_key']
        login_user_key = login_user_key_result['login_user_key']


        self._pipeline.sadd(new_user_key, user_id).sadd(login_user_key, user_id).execute()


    # 判断用户是否为新增用户
    def check_newuser(self, login_time, main_channel, sub_channel, game_id, user_id):

        # 由于判断是否是新用户,所以无法直接获得注册时间,根据登陆时间去寻找,为了函数需求,创建时间写空
        user_key = login_key(login_time, main_channel, sub_channel, game_id)
        check_user_key = user_key['new_user_key']

        user_status = self._conn.sismember(check_user_key, user_id)

        if user_status == 1:
            return True
        else:
            return False


    # 统计付费用户,付费金额,总订单数,成功订单数,
    def user_pay(self, pay_time, main_channel, sub_channel, game_id, user_id, pay_money, order_id):

        pay_key_result = pay_key(pay_time, main_channel, sub_channel, game_id)
        pay_money_int = int(pay_money)

        pay_user_key = pay_key_result['pay_user_key']
        pay_money_key = pay_key_result['pay_money_key']
        pay_succorder_key = pay_key_result['pay_succorder_key']


        pay_new_user_key = pay_key_result['pay_new_user_key']
        pay_new_money_key = pay_key_result['pay_new_money_key']
        pay_new_succorder_key = pay_key_result['pay_new_succorder_key']

        user_status = self.check_newuser(pay_time, main_channel, sub_channel, game_id, user_id)

        # 统计总付费人数,统计总付费金额,统计总付费成功订单数
        self._pipeline.sadd(pay_user_key, user_id).incr(pay_money_key, pay_money_int)\
            .sadd(pay_succorder_key, order_id).execute()

        # 判断是否为新用户
        if user_status:
            # 统计新增付费人数,统计新增用户付费金额,统计新增用户成功订单数
            self._pipeline.sadd(pay_new_user_key, user_id).incr(pay_new_money_key, pay_money_int)\
                .sadd(pay_new_succorder_key, order_id).execute()
